package credit;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


import net.sf.json.JSONObject;

import java.security.cert.CertificateException;




public class HttpClientUtil {

	public static final Logger log = Logger.getLogger(HttpClientUtil.class);

	public static String getResponseBodyAsString(String url) {
		String str = null;

		HttpURLConnection conn = null;
		try {
			// Create a trust manager that does not validate certificate chains
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] certs, String authType) {
				}

				public void checkServerTrusted(X509Certificate[] certs, String authType) {
				}
			} };
			// Install the all-trusting trust manager
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

			URL url_2 = new URL(url);
			conn = (HttpURLConnection) url_2.openConnection();
			conn.connect();

			System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage());
			BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			str = r.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;

		// try {
		// HttpClient client = new HttpClient();
		// // 璁剧疆浠ｇ悊鏈嶅姟鍣ㄥ湴鍧�拰绔彛
		// //
		// client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
		// // 浣跨敤 GET 鏂规硶 锛屽鏋滄湇鍔″櫒闇�閫氳繃 HTTPS 杩炴帴锛岄偅鍙渶瑕佸皢涓嬮潰 URL 涓殑 http 鎹㈡垚 https
		// HttpMethod method = new GetMethod(url);
		// method.setRequestHeader("Connection", "close");
		// // 浣跨敤POST鏂规硶
		// // HttpMethod method = new PostMethod("http://java.sun.com");
		// client.executeMethod(method);
		// // 鎵撳嵃杩斿洖鐨勪俊鎭�
		// str = method.getResponseBodyAsString();
		// // 閲婃斁杩炴帴
		// method.releaseConnection();
		// } catch (Exception e) {
		// log.info(e.getMessage());
		// e.printStackTrace();
		// }
		// return str;
	}

	/**
	 * 浣跨敤POST鏂瑰紡鎻愪氦鏁版嵁
	 * 
	 * @return
	 * @throws ErrorException 
	 * @throws IOException
	 */
	public static String getPostMethod(String url, Map<String, String> params)  {
		URL u = null;
		HttpURLConnection con = null;
		//鏋勫缓璇锋眰鍙傛暟
		StringBuffer sb = new StringBuffer();
		if(params!=null){
		for (Entry<String, String> e : params.entrySet()) {
		sb.append(e.getKey());
		sb.append("=");
		sb.append(e.getValue());
		sb.append("&");
		}
		if(sb.toString().length()>0){
			sb.substring(0, sb.length() - 1);
		}
		}
		System.out.println("send_url:"+url);
		System.out.println("send_data:"+sb.toString());
		//灏濊瘯鍙戦�璇锋眰
		try {
		u = new URL(url);
		con = (HttpURLConnection) u.openConnection();
		con.setRequestMethod("POST");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches(false);
		con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/*		con.setRequestProperty("oUa", "oUa=0|Nexus 5|4.4.4|1080*1776|9d05ab13-7c6c-30b6-b921-e1dc0ecbb503|46002|0|google");
		con.setRequestProperty("version", "1.3.5|1.3.5|4.5.6");
		con.setRequestProperty("device", "123|ert|345");
		con.setRequestProperty("oService", "1000093331000800000");*/
		con.setRequestProperty("token","3dd813b021fa427eadee211284ec8ee0" );
        con.setRequestProperty("appName", "xmdk");
		OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
		
		osw.write(sb.toString());
		osw.flush();
		osw.close();
		} catch (Exception e) {
		    e.printStackTrace();
		    
		} finally {
		if (con != null) {
		con.disconnect();
		}
	}
		 
		//璇诲彇杩斿洖鍐呭
		StringBuffer buffer = new StringBuffer();
		try {
		BufferedReader br = new BufferedReader(new InputStreamReader(con
		.getInputStream(), "UTF-8"));
		System.out.println("鐘舵� [ "+con.getResponseCode()+" ]");
		String temp;
		while ((temp = br.readLine()) != null) {
		buffer.append(temp);
		}
		} catch (Exception e) {
		e.printStackTrace();
		}
		
		return buffer.toString();
		
	}

	/**
	 * 蹇借璇佷功HostName
	 */
	private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
		public boolean verify(String s, SSLSession sslsession) {
			System.out.println("WARNING: Hostname is not matched for cert.");
			return true;
		}
	};

	/**
	 * Ignore Certification
	 */
	private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {

		private X509Certificate[] certificates;

		public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
			if (this.certificates == null) {
				this.certificates = certificates;
				System.out.println("init at checkClientTrusted");
			}
		}

		public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
			if (this.certificates == null) {
				this.certificates = ax509certificate;
				System.out.println("init at checkServerTrusted");
			}
			// for (int c = 0; c < certificates.length; c++) {
			// X509Certificate cert = certificates[c];
			// System.out.println(" Server certificate " + (c + 1) + ":");
			// System.out.println("  Subject DN: " + cert.getSubjectDN());
			// System.out.println("  Signature Algorithm: "
			// + cert.getSigAlgName());
			// System.out.println("  Valid from: " + cert.getNotBefore());
			// System.out.println("  Valid until: " + cert.getNotAfter());
			// System.out.println("  Issuer: " + cert.getIssuerDN());
			// }

		}

		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
	};

	public static String getMethod(String urlString) {

		ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
		try {
			URL url = new URL(urlString);
			/*
			 * use ignore host name verifier
			 */
			HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

			// Prepare SSL Context
			TrustManager[] tm = { ignoreCertificationTrustManger };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());

			// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			connection.setSSLSocketFactory(ssf);

			InputStream reader = connection.getInputStream();
			byte[] bytes = new byte[512];
			int length = reader.read(bytes);
			do {
				buffer.write(bytes, 0, length);
				length = reader.read(bytes);
			} while (length > 0);

			// result.setResponseData(bytes);
			System.out.println(buffer.toString());
			reader.close();

			connection.disconnect();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
		}
		String repString = new String(buffer.toByteArray());
		return repString;
	}

	/**
	 * 鐜板湪榛樿鐨刾ost杩炴帴
	 * @param postData
	 * @param postUrl
	 * @return
	 * @throws Exception
	 */
	public static String getTreaty(String postData, String postUrl) throws IOException {
		
		System.out.println(postData);

		OutputStreamWriter out = null;
		StringBuffer result = new StringBuffer();
		try {
			URL url = new URL(postUrl);
			String line = "";
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(60000);
			conn.setRequestProperty("Content-Length", "" + postData.length());
			
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(postData);
			out.flush();
			out.close();
			
			int responseCode = conn.getResponseCode();
			
			System.out.println("褰撳墠鐨剅esponseCode涓猴細 [ "+responseCode +" ] ");
			
			/**
			 * 瀵箁esponseCode鐨勪竴浜涘垽鏂�
			 */
			if(responseCode == 200){ 
				
			}else if(responseCode == 302 ){
				
			}else if(responseCode >=400 && responseCode <500){
				System.out.println("4XX閿欒锛屾湇鍔″櫒鍐呴儴閿欒锛岃閿欒涓嶉渶瑕佸惎鍔ㄥ畾鏃朵换鍔★紝璇烽�鐭ヨ矗浠讳汉妫�煡鏈嶅姟鍣紝鍦板潃涓猴細 [ " + postUrl +" ] ");
			}else if(responseCode >=500 && responseCode < 600){
				System.out.println("5XX閿欒锛岃皟鐢ㄥ湴鍧�殑鏈嶅姟鍣ㄧ▼搴忛敊璇紝璇ラ敊璇渶瑕佸惎鍔ㄥ畾鏃朵换鍔″彂閫侊紝鍦板潃涓猴細 [ " + postUrl +" ] ");
			}
			
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result.append(line).append("\n");
			}
		}catch(IOException e){
			
		}finally {
		
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return result.toString().trim();
	}

	public static void main(String[] args) {
		System.out
				.println(HttpClientUtil
						.getResponseBodyAsString("https://openapi.360.cn/pay/verify_mobile_notification.json?app_key=a28ddfc40d430eedaff4c036befae2db&product_id=2714023735831272&amount=500&app_uid=22133437&order_id=1302231702974537627&app_order_id=2013022318570308547911&sign_type=md5&sign_return=1663acd29849b75ab99e43087c41ef97&client_id=a28ddfc40d430eedaff4c036befae2db&client_secret=32a7961d01b7486377bc46eec46864bb"));
	}

	public static String getTreatyText(String postData, String postUrl) {
		System.out.println(postData);

		OutputStreamWriter out = null;
		StringBuffer result = new StringBuffer();
		try {
			URL url = new URL(postUrl);
			String line = "";
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "text/xml");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setRequestProperty("Content-Length", "" + postData.length());
			
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(postData);
			out.flush();
			out.close();
			
			int responseCode = conn.getResponseCode();
			
			System.out.println("褰撳墠鐨剅esponseCode涓猴細 [ "+responseCode +" ] ");
			
			/**
			 * 瀵箁esponseCode鐨勪竴浜涘垽鏂�
			 */
			if(responseCode == 200){ 
				
			}else if(responseCode == 302 ){
				
			}else if(responseCode >=400 && responseCode <500){
				System.out.println("4XX閿欒锛屾湇鍔″櫒鍐呴儴閿欒锛岃閿欒涓嶉渶瑕佸惎鍔ㄥ畾鏃朵换鍔★紝璇烽�鐭ヨ矗浠讳汉妫�煡鏈嶅姟鍣紝鍦板潃涓猴細 [ " + postUrl +" ] ");
			}else if(responseCode >=500 && responseCode < 600){
				System.out.println("5XX閿欒锛岃皟鐢ㄥ湴鍧�殑鏈嶅姟鍣ㄧ▼搴忛敊璇紝璇ラ敊璇渶瑕佸惎鍔ㄥ畾鏃朵换鍔″彂閫侊紝鍦板潃涓猴細 [ " + postUrl +" ] ");
			}
			
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result.append(line).append("\n");
			}
		}catch(IOException e){
			
		}finally {
		
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return result.toString().trim();
	}
	
	
	/**
     * 鍚戞寚瀹歎RL鍙戦�GET鏂规硶鐨勮姹�
     * 
     * @param url
     *            鍙戦�璇锋眰鐨刄RL
     * @param param
     *            璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋�
     * @return URL 鎵�唬琛ㄨ繙绋嬭祫婧愮殑鍝嶅簲缁撴灉
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            
            log.info("请求参数:[ "+urlNameString+" ]");
            
            URL realUrl = new URL(urlNameString);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
            URLConnection connection = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬�
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 寤虹珛瀹為檯鐨勮繛鎺�
            connection.connect();
            // 鑾峰彇鎵�湁鍝嶅簲澶村瓧娈�
            Map<String, List<String>> map = connection.getHeaderFields();
            // 閬嶅巻鎵�湁鐨勫搷搴斿ご瀛楁
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("鍙戦�GET璇锋眰鍑虹幇寮傚父锛� + e");
            e.printStackTrace();
        }
        // 浣跨敤finally鍧楁潵鍏抽棴杈撳叆娴�
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
    
}
